// pages/home/home.js
import Dialog from '@vant/weapp/dialog/dialog';
import { areaList } from '../../components/area-data/dist/data';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //定时器
    identity:'',
      realTime:null,
      show:false,
      elderId:'',
      elders:[],
      elderName:'',
      city1:'',
      city:'',
      location1:'',
      location:'',
      value1: 0,
      option1: [
        
      ],
        areaList,
        identity:'',
				nickName:'forever',
				swiperList:
				[
					{
						id : 1,
						image_src: "/static/background1.jpg"
					},
					{
						id : 2,
						image_src: "/static/background2.jpg"
					}
				],
				serviceList:
				[
					{
						id: 1,
						image_src:"/static/健康.png",
            name:"健康监测",
            content:'health'
					},
					{
						id: 2,
						image_src:"/static/通话.png",
            name:"通话提醒",
            content:'reminder'
					},
					{
						id: 3,
						image_src:"/static/账单.png",
            name:"账单查询",
            content:'money'
					},
					{
						id: 4,
						image_src:"/static/药品.png",
            name:"用药情况",
            content:'medicine'
					},
					{
						id: 5,
						image_src:"/static/活动.png",
            name:"活动情况",
            content:'activity'
					},
					{
						id: 6,
						image_src:"/static/饮食.png",
            name:"饮食记录",
            content:'food'
					},
					{
						id: 7,
						image_src:"/static/建议.png",
            name:"建议箱",
            content:'recommend'
					},
					{
						id: 8,
						image_src:"/static/推文.png",
            name:"亲情记录",
            content:'record'
					}
				],
			

  },
 
  //跳转排行榜界面
  attendance(){
    wx.navigateTo({
      url: '/subpkg/attendance/attendance',
    })
  },

   //取消收藏
   cancelCollect(e){
    var index = e.currentTarget.dataset.index
    var articleList = this.data.articleList
    articleList[index].icon = '/static/收藏 (1).png'
    this.setData({
      articleList:articleList
    })
    wx.request({
      url: 'https://zhixiao.site:8080/article/cancel/',
      data:{
        userId:wx.getStorageSync('userid'),
        articleId:articleList[index].id
      },
      success:(res)=>{
        console.log(res)
      }
    })

  },
  collect(e){
    var index = e.currentTarget.dataset.index
    var articleList = this.data.articleList
    articleList[index].icon = articleList[index].icon === '/static/收藏 (1).png' ? '/static/收藏 (2).png' : '/static/收藏 (1).png'
    this.setData({
      articleList:articleList
    })
    wx.request({
      url: 'https://zhixiao.site:8080/article/collect',
      data:{
        userId:wx.getStorageSync('userid'),
        articleId:this.data.articleList[index].id
      },
      success:(res)=>{
        console.log(res)
      }
    })
  },
  
  onCancel(){
    this.setData({
      show:false
    })
  },
  onConfirm(){
    this.setData({
      show:false,
    })
    this.setData({
      location:this.data.location1,
      city:this.data.city1
    })
  },
  onChange(e){

    var name = e.detail.values[2].name
    var city = e.detail.values[1].name
    console.log(e.detail.values[2].name)
    this.setData({
      location1:name,
      city1:city
    })
  },
  showPopup() {
    this.setData({ show: true });
  },
  locate(){

  },
  navigator(e){
    var identity = wx.getStorageSync('identity')
    console.log(wx.getStorageSync('elderId'))
    if(identity === '游客'){
      Dialog.confirm({
        title: '提醒',
        message: '您当前是游客身份，请绑定后享受更多服务!',
      })
        .then(() => {
          // on confirm
          
          wx.redirectTo({
            url: '/subpkg_worker/login/login',
          })
        })
        .catch(() => {
          // on cancel
        });
    }
    else if(wx.getStorageSync('elderId')===''){
      Dialog.confirm({
        title: '提醒',
        message: '您还未绑定老人,请先绑定老人后享受更多服务!',
      })
        .then(() => {
          // on confirm
          wx.navigateTo({
            url: '/subpkg/my/bindelder/bindelder',
          })
        })
        .catch(() => {
          // on cancel
        });
    }
    else{
      var index = e.currentTarget.dataset.index
      var serviceList = this.data.serviceList

      wx.navigateTo({
        url: `/subpkg/${serviceList[index].content}/${serviceList[index].content}`
      })
    }
  },
  click(){
    wx.navigateTo({
      url: '/subpkg/sign/sign',
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(123)
  },
  //更换老人
  changeElder(e){
    var index = e.detail
    console.log(index)
    var elderName = this.data.option1[index].text
    var elderlyId = this.data.option1[index].id
    wx.setStorageSync('elderId', elderlyId)
    this.setData({
      elderName:elderName,
      elderId:elderlyId,
    })
  },
  queryElders(){
    wx.request({
      url: 'https://zhixiao.site:8080/client/getElderIds',
      data:{
        userId:wx.getStorageSync('userid')
      },
      success:(res)=>{
        
      },
      complete:(res)=>{
        //绑定老人
        console.log(res)
        if(res.data.data.length === 0){
          this.setData({
            elderName:'暂无'
          })
          return
        }
        var elders = res.data.data
        wx.setStorageSync('elderId', elders[0].elderlyId)
        this.setData({
          elders:elders,
          elderName:elders[0].name
        })
        var option1 = []
        for(var i in this.data.elders){
          var elder = {}
          elder.text = this.data.elders[i].name
          elder.value = parseInt(i)
          elder.id = this.data.elders[i].elderlyId
          option1.push(elder)
        }
        this.setData({
          option1:option1
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    wx.request({
      url: `https://zhixiao.site:8080/identity-verification/get-messages?userId=${wx.getStorageSync('userid')}`,
      success:(res)=>{
        console.log(res.data.data)
        var msg = res.data.data
        for(var i in msg){
          if(msg[i].type==='角色绑定'){
            return
          }
        }
        if(wx.getStorageSync('identity') === '游客'){
          Dialog.confirm({
            title: '提醒',
            message: '您当前是游客身份，请绑定后享受更多服务!',
          })
            .then(() => {
              // on confirm
              wx.redirectTo({
                url: '/subpkg_worker/login/login',
              })
            })
            .catch(() => {
              // on cancel
    
    
            });
        }
        }
      })
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(wx.getStorageSync('identity')==='家属'){
      this.queryElders()
    }
    this.setData({
      identity:wx.getStorageSync('identity'),
      nickName:wx.getStorageSync('nickName')
    })
    const that = this
    var realTime = setInterval(function(){
      that.quergMsg()
      console.log('循环请求中')
    },5000)
    this.setData({
      realTime:realTime
    })
    
  },
  quergMsg(){
    
    wx.request({
      url: 'https://zhixiao.site:8080/client/login',
      data:{
        openid:wx.getStorageSync('openid')
      },
      //后端返回用户对应身份，养老院名称
      success:(res2)=>{
        console.log(1212)
        console.log(res2)
        var JSESSIONID = res2.cookies[0]
        wx.setStorageSync('JSESSIONID', JSESSIONID)
        wx.setStorageSync('userid', res2.data.data.id)
        wx.setStorageSync('identity', res2.data.data.identity)
        this.setData({
          identity:res2.data.data.identity
        })
        wx.setStorageSync('beadhouse', res2.data.data.careHomeName)
      },
      complete:(res2)=>{
        if(res2.data.data.identity==='老人'){
          console.log("老人")
          wx.reLaunch({
            url: '/elder/service/service',
          })
        }else if(res2.data.data.identity==='护工'){
          console.log("护工")
          wx.reLaunch({
            url: '/pages/elderList/elderList',
          })
        }
        this.queryElders()
       
      }
    })

    // wx.request({
    //   url: `https://zhixiao.site:8080/identity-verification/get-messages?userId=${wx.getStorageSync('userid')}`,
    //   success:(res)=>{
    //     //已经处理过的绑定信息存储到本地
    //     var bindMsg = wx.getStorageSync('bindMsg')
        
    //     //后端查出来的
    //     var msg = res.data.data
    //     var flag = 0
    //     for(var i in msg){
    //       if(bindMsg.indexOf(msg[i].id)===-1&&msg[i].status===1){
    //         flag = 1
    //         console.log(111)
    //         bindMsg.push(msg[i].id)
    //       }
    //     }
        
    //     wx.setStorageSync('bindMsg', bindMsg)
    //     if(flag===1){
    //       Dialog.confirm({
    //         title: '提醒',
    //         message: '您的申请信息已通过',
    //       })
    //         .then(() => {
    //           // on confirm
    //           // wx.redirectTo({
    //           //   url: '/subpkg/login/login',
    //           // })
    //           this.getUserInfo()
              
    //         })

    //     }
      
    //     }
    //   })
  },
  getUserInfo(){
    wx.request({
      url: 'https://zhixiao.site:8080/client/login',
      data:{
        openid:wx.getStorageSync('openid')
      },
      //后端返回用户对应身份，养老院名称
      success:(res2)=>{
        console.log(1212)
        console.log(res2)
        var JSESSIONID = res2.cookies[0]
        wx.setStorageSync('JSESSIONID', JSESSIONID)
        wx.setStorageSync('userid', res2.data.data.id)
        wx.setStorageSync('identity', res2.data.data.identity)
        this.setData({
          identity:res2.data.data.identity
        })
        wx.setStorageSync('beadhouse', res2.data.data.careHomeName)
        var bindMsg = wx.getStorageSync('bindMsg')===''?[]:wx.getStorageSync('bindMsg')
        wx.setStorageSync('bindMsg', bindMsg)
      },
      complete:(res2)=>{
        if(wx.getStorageSync('nickName')===''||wx.getStorageSync('avatarUrl')==='')
        {
          wx.redirectTo({
            url: '/subpkg/getnickName/getnickName',
          })
        }
       else{
        if(res2.data.data.identity==='老人'){
          console.log("老人")
          wx.reLaunch({
            url: '/elder/service/service',
          })
        }else if(res2.data.data.identity==='护工'){
          console.log("护工")
          wx.reLaunch({
            url: '/pages/elderList/elderList',
          })
        }
        this.queryElders()
       }
      }
    })
    wx.getUserProfile({
      desc: 'desc',
      success:(res)=>{
        console.log(res)
        // wx.setStorageSync('nickName', res.userInfo.nickName)
        // wx.setStorageSync('headPicture', res.userInfo.avatarUrl)
        wx.login({
          success: (res) => {
            if(res.code){
              console.log(res.code)
              
              wx.request({
                url: 'https://zhixiao.site:8080/client/getOpenId',
                data:{
                  code:res.code
                },
                //后端经过处理，传递给前端openid和session_key
                success:(res1) => {
                  console.log(11)
                  console.log(res1)
                  wx.setStorageSync('openid', res1.data.data.openid)
                  wx.setStorageSync('session_key', res1.data.data.session_key)
                  //根据openid来进行不同身份的登录
                  
                },
                complete:()=>{
                  wx.hideLoading()
                }
              })
             
            }
          },
        })
      
        
      },
      fail:()=>{
        console.log("登录失败")
      }
    })

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    var realTime = this.data.realTime
    clearInterval(realTime)
    this.setData({
      realTime:realTime
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    var realTime = this.data.realTime
    clearInterval(realTime)
    this.setData({
      realTime:realTime
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})